package cn.stronglink.assetmanage.business.check.view.sync;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.stronglink.assetmanage.BuildConfig;
import cn.stronglink.assetmanage.MainActivity;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.check.adapter.CheckListAdapter;
import cn.stronglink.assetmanage.business.check.adapter.CheckOrderAdapter;
import cn.stronglink.assetmanage.business.check.model.CheckModel;
import cn.stronglink.assetmanage.business.check.model.SyncAssetModel;
import cn.stronglink.assetmanage.business.check.model.SyncModel;
import cn.stronglink.assetmanage.business.check.presenter.SyncAssetPresenter;
import cn.stronglink.assetmanage.business.check.presenter.SyncListPresenter;
import cn.stronglink.assetmanage.business.check.view.detail.CheckSyncDetailFragment;
import cn.stronglink.assetmanage.business.task.model.ITaskSyncListener;
import cn.stronglink.assetmanage.business.task.model.OrderType;
import cn.stronglink.assetmanage.business.task.model.TaskSyncModel;
import cn.stronglink.assetmanage.dao.AssetDao;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.index.base.BaseChildFragment;
import cn.stronglink.assetmanage.index.entity.PromissionEntity;
import cn.stronglink.assetmanage.index.view.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ImageUtils;
import cn.stronglink.assetmanage.utils.ToastUtil;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 待同步表单列表
 */
public class SyncAssetFragment extends BaseChildFragment implements View.OnClickListener, ITaskSyncListener {
    protected Activity mActivity;
    String orderNo;
    private Button btn_check_sync;
    private CheckOrderAdapter orderAdapter;
    private SyncAssetModel syncAssetModel;
    private SyncAssetView syncAssetView;
    //待同步表单资产列表
    private RecyclerView rv_checksync_list;
    private LinearLayoutManager layoutManager;
    private TextView txt_left_title;
    private List<Asset> assetList = null;
    private TextView txt_title_right, txt_title_left, txt_main_title;
    private Check mCheck;
    private TaskSyncModel taskSyncModel;

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        try {
            if (!isVisible) {
                return;
            }
            Bundle bundle = getArguments();
            if (bundle != null) {
                orderNo = bundle.getString(Constants.CHECK_IN_DETAIL_NO);
                if (orderNo != null && !"".equals(orderNo)) {
                    mCheck = syncAssetModel.getCheckByOrderNo(orderNo);
                    setCheckDta();
                    assetList = syncAssetModel.getDataByOrderNo(orderNo);
                    syncAssetView.setOrderData(assetList);
                    syncAssetView.showAssetTitle(syncAssetModel.getCheckByOrderNo(orderNo));
                    orderAdapter.notifyDatasChanged(assetList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setCheckDta() {
        if (mCheck.getId_() != null && !mCheck.getId_().isEmpty()) {
            mCheck.setId(Long.valueOf(mCheck.getId_()));
        }
        List<Asset> assetList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT)
                .getAssetDao().queryBuilder().where(AssetDao.Properties.OrderNo.eq(mCheck.getId_())).list();
        if (assetList != null && assetList.size() > 0) {
            for (Asset asset : assetList) {
                if (asset.getId_() != null && !asset.getId_().isEmpty()) {
                    asset.setId(Long.valueOf(asset.getId_()));
                }
                if (asset.getBrandId_() != null && !asset.getBrandId_().isEmpty()) {
                    asset.setBrandId(Long.valueOf(asset.getBrandId_()));
                }
                if (asset.getModelId_() != null && !asset.getModelId_().isEmpty()) {
                    asset.setModelId(Long.valueOf(asset.getModelId_()));
                }
                if (asset.getTypeId_() != null && !asset.getTypeId_().isEmpty()) {
                    asset.setTypeId(Long.valueOf(asset.getTypeId_()));
                }
                if (asset.getDatacenterId_() != null && !asset.getDatacenterId_().isEmpty()) {
                    asset.setDatacenterId(Long.valueOf(asset.getDatacenterId_()));
                }
                if (asset.getRoomId_() != null && !asset.getRoomId_().isEmpty()) {
                    asset.setRoomId(Long.valueOf(asset.getRoomId_()));
                }
                if (asset.getPictureUri() != null && !"".equals(asset.getPictureUri())) {
                    String imgPath = ImageUtils.imageToBase64(asset.getPictureUri());
                    asset.setImagpath(imgPath);
                }
            }
            mCheck.setAssetList(assetList);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_sync_asset, container, false);
        initViewAndData(rootView);
        return rootView;
    }

    private void initViewAndData(View view) {
        try {
            txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
            txt_main_title.setText("入库待同步");
            txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
            txt_title_right.setVisibility(View.INVISIBLE);
            txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
            txt_title_left.setVisibility(View.VISIBLE);
            assetList = new ArrayList<>();
            btn_check_sync = (Button) view.findViewById(R.id.btn_check_sync);
            btn_check_sync.setOnClickListener(this);
            rv_checksync_list = view.findViewById(R.id.rv_checksync_list);
            rv_checksync_list.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
            orderAdapter = new CheckOrderAdapter(getActivity());
            layoutManager = new LinearLayoutManager(this.getActivity(), LinearLayout.VERTICAL, false);
            rv_checksync_list.setLayoutManager(layoutManager);
            rv_checksync_list.setAdapter(orderAdapter);
            orderAdapter.setOnItemClickListener(new onRecyclerListener() {
                @Override
                public void onItemClicked(View v, int postion) {
                    //跳转到详情页
                    if (assetList != null && assetList.size() > 0) {
                        MainActivity activity = (MainActivity) getActivity();
                        PromissionEntity pe = new PromissionEntity();
                        pe.setFragment(new CheckSyncDetailFragment());
                        pe.setPosition(MainActivity.FRAGMENT_CUSTOM_ID);
                        pe.setTitle("待同步详情");
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constants.CHECK_IN_DETAIL_NO, assetList.get(postion).getAsset_id_key());
                        pe.setBundle(bundle);
                        activity.onEventRegister(pe);
                    }


                }
            });
            syncAssetModel = new SyncAssetModel();
            taskSyncModel = new TaskSyncModel();
            taskSyncModel.setListener(this);
            syncAssetView = new SyncAssetView(this, view, orderAdapter);
            txt_left_title = this.getActivity().findViewById(R.id.txt_left_title);
            txt_left_title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mActivity.onBackPressed();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.toastShort("没有数据显示");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keycode, KeyEvent keyEvent) {
                if (keycode == KeyEvent.KEYCODE_BACK) {
                    mActivity.onBackPressed();
                    return true;
                }
                return false;
            }
        });
    }

    private void showJsonData(String json) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setMessage("提交的json串信息:" + json + "\n" + "应用版本:" + BuildConfig.VERSION_CODE);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create();
        builder.show();
    }

    @Override
    public void onFail(String orderNo, OrderType orderType, Exception e, int sum) {
        syncAssetView.showToast("提交数据失败" + orderType + sum + e.getMessage());
        syncAssetView.hideProgressDialog();
    }    @Override
    public void onClick(View v) {
        //同步已经入库数据
        try {
            syncAssetView.showProgressDialog(getString(R.string.check_wait_sync));
//            taskSyncModel.uploadCheckList(syncAssetModel.getDataByOrderNoDistince());
            //TODO 显示提交的Json数据
//            Gson gson = new Gson();
//            String json = gson.toJson(mCheck);
//            if (json != null) {
//                showJsonData(json);
//            }
            taskSyncModel.uploadCheck(mCheck);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.toastShort("同步数据失败");
        }

    }

    @Override
    public void onSucces(String orderNo, OrderType orderType, int sum) {
        syncAssetView.showToast("数据同步成功");
        syncAssetView.hideProgressDialog();
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mActivity.onBackPressed();
            }
        });

    }




}
